package com.lw.leetcode.str.a;

/**
 * Created with IntelliJ IDEA.
 * 面试题 01.06. 字符串压缩
 *
 * @author liw
 * @version 1.0
 * @date 2021/7/29 15:27
 */
public class CompressString {
    public String compressString(String S) {
        if (S == null || S.length() == 0) {
            return S;
        }
        int length = S.length();
        StringBuilder sb = new StringBuilder(length);
        int cnt = 1;
        char ch = S.charAt(0);
        for (int i = 1; i < length; ++i) {
            if (ch == S.charAt(i)) {
                cnt++;
            } else {
                sb.append(ch);
                sb.append(cnt);
                ch = S.charAt(i);
                cnt = 1;
            }
        }
        sb.append(ch);
        sb.append(cnt);
        return sb.length() >= length ? S : sb.toString();
    }

}
